package com.example.csdn.service.impl;

import com.example.csdn.DTO.ArticleAddDTO;
import com.example.csdn.mapper.ArticleMapper;
import com.example.csdn.pojo.Article;
import com.example.csdn.pojo.PageBean;
import com.example.csdn.service.ArticleService;
import com.example.csdn.utils.ThreadLocalUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper;

    @Override
    public PageBean<Article> articleList(Integer pageNum, Integer pageSize, Integer categoryId, String state) {
        //开启分页
        PageBean<Article> pb = new PageBean<>();
        PageHelper.startPage(pageNum,pageSize);

        Map<String,Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        List<Article> list = articleMapper.articleList(categoryId, state, userId);
        Page<Article> page = (Page<Article>) list;
        pb.setTotal(page.getTotal());
        pb.setItems(page.getResult());
        return pb;
    }

    @Override
    public void add(ArticleAddDTO articleAddDTO) {
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        articleAddDTO.setUserId(userId);
        articleMapper.add(articleAddDTO);
    }

    @Override
    public void delete(Integer id) {
        articleMapper.delete(id);
    }

    @Override
    public void update(Article article) {
        articleMapper.update(article);
    }

    @Override
    public Article getArticleById(Integer id) {
        return articleMapper.getArticleById(id);
    }
}
